#!/bin/sh

#export PATH="/mnt/ESensor/bin:$PATH"

cfgAlarmConfPath="/mnt/ESensor/etc/alarm.conf"
cfgAlarmInConfPrefix="ALARM_OUT.DROPBOX"
#Default configuration file
CONFIG_FILE=/tmp/dropbox_uploader.conf
APPKEY=`/mnt/ESensor/bin/config -f $cfgAlarmConfPath -p $cfgAlarmInConfPrefix.[0].AppKey`
APPSECRET=`/mnt/ESensor/bin/config -f $cfgAlarmConfPath -p $cfgAlarmInConfPrefix.[0].AppSecret`

#Don't edit these...
API_REQUEST_TOKEN_URL="https://api.dropbox.com/1/oauth/request_token"
API_USER_AUTH_URL="https://www2.dropbox.com/1/oauth/authorize"
API_ACCESS_TOKEN_URL="https://api.dropbox.com/1/oauth/access_token"
APP_CREATE_URL="https://www2.dropbox.com/developers/apps"
USER_CALLBACK="http://$HTTP_HOST/ESensor/db_verifyAuth.cgi"
RESPONSE_FILE="/tmp/du_resp_$RANDOM"

umask 077

#Returns unix timestamp
utime ()
{
    echo $(date +%s)
}

#Remove temporary files
remove_temp_files ()
{
    rm -fr $RESPONSE_FILE
}

#TOKEN REQUESTS
time=$(utime)
/mnt/ESensor/bin/curl -s --show-error -k -i -o $RESPONSE_FILE --data "oauth_consumer_key=$APPKEY&oauth_signature_method=PLAINTEXT&oauth_signature=$APPSECRET%26&oauth_timestamp=$time&oauth_nonce=$RANDOM" "$API_REQUEST_TOKEN_URL"
OAUTH_TOKEN_SECRET=$(sed -n -e 's/oauth_token_secret=\([a-z A-Z 0-9]*\).*/\1/p' "$RESPONSE_FILE")
OAUTH_TOKEN=$(sed -n -e 's/.*oauth_token=\([a-z A-Z 0-9]*\)/\1/p' "$RESPONSE_FILE")

if [ ! -n "$OAUTH_TOKEN" -a -n "$OAUTH_TOKEN_SECRET" ]; then
       echo -ne " FAILED\n\n Verify your App key and secret...\n\n"
       remove_temp_files
       exit 1
fi

echo "APPKEY:$APPKEY" > $CONFIG_FILE
echo "APPSECRET:$APPSECRET" >> $CONFIG_FILE
echo "OAUTH_TOKEN:$OAUTH_TOKEN" >> $CONFIG_FILE
echo "OAUTH_TOKEN_SECRET:$OAUTH_TOKEN_SECRET" >> $CONFIG_FILE
                                                
remove_temp_files

#USER AUTH - Wait for auth
cat  << EOF
Content-type: text/html

<html>
<head>
<script type="text/javascript">
//<![CDATA[
window.location.href="${API_USER_AUTH_URL}?oauth_token=$OAUTH_TOKEN&oauth_callback=${USER_CALLBACK}";
</script>
//]]>
</head>
</html>
EOF

sync
exit 0
